<template>
  <div style="padding: 10px">
    <el-form
      :model="item"
      ref="ruleForm"
      :rules="rules"
      label-width="100px"
      class="demo-ruleForm"
      style="width: 50%"
    >
      <el-form-item label="借款额度" prop="borrowAmount">
        <el-input v-model="item.borrowAmount"></el-input>
      </el-form-item>

      <el-form-item label="积分区间" prop="integralStart">
        <el-row>
          <el-col :span="8">
            <el-input v-model="item.integralStart"></el-input>
          </el-col>
          <el-col :span="1"> -- </el-col>
          <el-col :span="8">
            <el-input v-model="item.integralEnd"></el-input>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="handleSaveOrUpdate"> 提交 </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import integralGradeApi from "@/api/integralGrade";
export default {
  data() {
    return {
      item: {},
      rules: {
        borrowAmount: [
          { required: true, message: "请输入借款额度", trigger: "blur" },
        ],
        integralStart: [
          { required: true, message: "请输入积分区间", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    //this.$route 代表访问当前页面的路由对象，只包含当前页面的路由的配置信息
    // console.log(this.$route);
    //1、获取请求参数id： url?id=xxx  （this.$router.push(`/integral-grade/edit?id=${row.id}`); ）
    // console.log(this.$route.query.id);
    //2、获取路径参数id：url/id值
    // console.log(this.$route.params.id);
    //更新时根据id查询积分等级回显 ，没有获取到id代表新增
    if (this.$route.params.id) {
      this.getById();
    }
  },
  methods: {
    getById() {
      integralGradeApi.getById(this.$route.params.id).then((r) => {
        //r代表响应体对象(查询成功响应体设置的是R对象的json)
        this.item = r.data.item;
      });
    },
    handleSaveOrUpdate() {
      if (this.$route.params.id) {
        //更新
        this.handleUpdate();
      } else {
        //新增
        this.handleSave();
      }
    },
    handleUpdate() {
      integralGradeApi.update(this.item).then((r) => {
        this.$message.success("更新积分等级成功");
        //清空item缓存
        this.item = {};
        //通过路由跳转到积分等级列表页面
        this.$router.push("/integral-grade/list");
      });
    },
    handleSave() {
      integralGradeApi.save(this.item).then((r) => {
        this.$message.success("新增积分等级成功");
        //清空item缓存
        this.item = {};
        //通过路由跳转到积分等级列表页面
        this.$router.push("/integral-grade/list");
      });
    },
  },
};
</script>
